package http.network;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author zhuhuogeng
 * @date 2017/5/5.
 */
public class HttpCallback implements Callback {
  private static Logger log = LoggerFactory.getLogger("netLog");

  private int successEventType;
  private int failureEventType;
  private long itemId;

  @Override
  public void onFailure(Call call, IOException e) {
    log.error("send http request fail. offer id {}, url {}", itemId, call.request().url().toString());
    log.error("send http request fail reason !", e);
//    EventBus.getInstance().push(failureEventType, itemId, null);
    HttpCallBackPool.getInstance().release(this);
  }

  @Override
  public void onResponse(Call call, Response response) throws IOException {
    HttpResponse httpResponse = buildHttpResponse(response);
//    EventBus.getInstance().push(successEventType, itemId, httpResponse);
    HttpCallBackPool.getInstance().release(this);
  }

  private HttpResponse buildHttpResponse(Response response) {
    HttpResponse httpResponse = new HttpResponse();
    httpResponse.setRequest(response.request());
    httpResponse.setCode(response.code());
    httpResponse.setLocation(response.header("Location"));
    httpResponse.setContentType(response.body().contentType());
    httpResponse.setRefresh(response.header("Refresh"));
    try {
      httpResponse.setBody(response.body().string());
    } catch (IOException e) {
      log.error("get response body fail. url: {}", response.request().url().toString());
      httpResponse.setBody("");
    }
    return httpResponse;
  }

  public void setItemId(long itemId) {
    this.itemId = itemId;
  }

  public void setSuccessEventType(int successEventType) {
    this.successEventType = successEventType;
  }

  public void setFailureEventType(int failureEventType) {
    this.failureEventType = failureEventType;
  }
}
